package com.china08.yxyapi.service.jpush.impl;

import java.util.Map;

import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.china08.yxyapi.config.JpushConfig;
import com.china08.yxyapi.service.jpush.JpushService;

import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import cn.jpush.api.schedule.ScheduleResult;

@Service
public class JpushServiceImpl implements JpushService {

    @Value(value = "${spring.profiles.active}")
    private String profiles;

    private static final Logger LOGGER = LoggerFactory.getLogger(JpushServiceImpl.class);

    @Autowired
    private JpushConfig jpushConfig;

    @Override
    public void sendMessagePushToTags(String msgContent, String[] tags, String[] tag_ands) {
        // ##
        // 接收者不能为空
        if (tags == null || tags.length == 0) {//
            return;
        }

        // 设置运行模式
        boolean pattern = false;
        String patternStr = "[DEV]";
        if (profiles.equals("pro") || profiles.equals("prohrb")) {
            pattern = true;
            patternStr = "[PRO]";
        }

        Message message = new Message.Builder().setMsgContent(msgContent).build();
        // 组装PushPayload
        PushPayload pushPayload = PushPayload.newBuilder()
                .setOptions(Options.newBuilder().setApnsProduction(pattern).setTimeToLive(60 * 60 * 24 * 10).build())
                // tag参数
                .setAudience(
                        tag_ands == null ? Audience.newBuilder().addAudienceTarget(AudienceTarget.tag(tags)).build()
                                : Audience.newBuilder().addAudienceTarget(AudienceTarget.tag(tags))
                                        .addAudienceTarget(AudienceTarget.tag_and(tag_ands)).build())
                // 消息
                .setMessage(message)
                // 平台
                .setPlatform(Platform.android_ios())//
                .build();

        try {
            LOGGER.info(patternStr + "发送消息Message开始");
            LOGGER.info("TAGS:" + ArrayUtils.toString(tags));
            PushResult result = jpushConfig.getInstance().sendPush(pushPayload);
            LOGGER.info(patternStr + "发送消息Message结束:" + result);
        } catch (Exception e) {
            // LOGGER.error("发送消息异常[PRO]", e);
            LOGGER.error(patternStr + "发送消息Message异常:" + e.getMessage());
            if (e instanceof APIRequestException) {
                APIRequestException ee = (APIRequestException) e;
                if (ee.getErrorCode() == 2002) { throw new RuntimeException(e); }
            }
        }
    }

    @Override
    public void sendNotificationPushToTags(String alert, String title, Map<String, String> extras, String[] tags,
            String[] tag_ands) {
        // ##
        // 接收者不能为空
        if (tags == null || tags.length == 0) {//
            return;
        }

        // 设置运行模式
        boolean pattern = false;
        String patternStr = "[DEV]";
        if (profiles.equals("pro") || profiles.equals("prohrb")) {
            pattern = true;
            patternStr = "[PRO]";
        }

        // Ios
        IosNotification iosNotification = IosNotification.newBuilder()
                // 详情
                .setAlert(title + ":" + alert)
                // 声音
                .setSound("default")
                // 拓展参数
                .addExtras(extras).build();

        // Android
        AndroidNotification androidNotification = AndroidNotification.newBuilder()
                // 标题
                .setTitle(title)
                // 详情
                .setAlert(alert)
                // 拓展参数
                .addExtras(extras).build();

        PushPayload payload = PushPayload.newBuilder()
                .setOptions(Options.newBuilder().setApnsProduction(pattern).setTimeToLive(60 * 60 * 24 * 10).build())
                // 平台
                .setPlatform(Platform.android_ios())
                // tag别名
                .setAudience(
                        tag_ands == null ? Audience.newBuilder().addAudienceTarget(AudienceTarget.tag(tags)).build()
                                : Audience.newBuilder().addAudienceTarget(AudienceTarget.tag(tags))
                                        .addAudienceTarget(AudienceTarget.tag_and(tag_ands)).build())
                // 提醒
                .setNotification(Notification.newBuilder()//
                        .addPlatformNotification(iosNotification)//
                        .addPlatformNotification(androidNotification)//
                        .build())
                .build();

        try {
            LOGGER.info(patternStr + "发送通知Notification开始");
            LOGGER.info("TAGS:" + ArrayUtils.toString(tags));
            PushResult result = jpushConfig.getInstance().sendPush(payload);
            LOGGER.info(patternStr + "发送通知Notification结束:" + result);
        } catch (Exception e) {
            // LOGGER.error("发送消息异常[PRO]", e);
            LOGGER.error(patternStr + "发送通知Notification异常:" + e.getMessage());
            if (e instanceof APIRequestException) {
                APIRequestException ee = (APIRequestException) e;
                if (ee.getErrorCode() == 2002) { throw new RuntimeException(e); }
            }
        }
    }

    /**
     * 定时推送---作业消息
     */
    @Override
    public void sendMessagePushToTagsTiming(String msgContent, String[] tags, String[] tag_ands, String date,
            String flag) {
        // ##
        // 接收者不能为空
        if (tags == null || tags.length == 0) {//
            return;
        }

        // 设置运行模式
        boolean pattern = false;
        String patternStr = "[DEV]";
        if (profiles.equals("pro") || profiles.equals("prohrb")) {
            pattern = true;
            patternStr = "[PRO]";
        }

        Message message = new Message.Builder().setMsgContent(msgContent).build();
        // 组装PushPayload
        PushPayload pushPayload = PushPayload.newBuilder()
                .setOptions(Options.newBuilder().setApnsProduction(pattern).setTimeToLive(60 * 60 * 24 * 10).build())
                // tag参数
                .setAudience(
                        tag_ands == null ? Audience.newBuilder().addAudienceTarget(AudienceTarget.tag(tags)).build()
                                : Audience.newBuilder().addAudienceTarget(AudienceTarget.tag(tags))
                                        .addAudienceTarget(AudienceTarget.tag_and(tag_ands)).build())
                // 消息
                .setMessage(message)
                // 平台
                .setPlatform(Platform.android_ios())//
                .build();

        try {
            LOGGER.info(patternStr + "发送消息Message开始");
            LOGGER.info("TAGS:" + ArrayUtils.toString(tags));
            JPushClient jPushClient = jpushConfig.getInstance(flag);
            ScheduleResult createSingleSchedule = jPushClient.createSingleSchedule("定时推送作业消息", date, pushPayload);
            LOGGER.info(patternStr + "发送消息Message结束:" + createSingleSchedule);
        } catch (Exception e) {
            // LOGGER.error("发送消息异常[PRO]", e);
            LOGGER.error(patternStr + "发送消息Message异常:" + e.getMessage());
            if (e instanceof APIRequestException) {
                APIRequestException ee = (APIRequestException) e;
                if (ee.getErrorCode() == 2002) { throw new RuntimeException(e); }
            }
        }
    }

    /**
     * 定时推送-----作业通知
     * 
     */
    @Override
    public void sendNotificationPushToTagsTiming(String alert, String title, Map<String, String> extras, String[] tags,
            String[] tag_ands, String date, String flag) {
        // ##
        // 接收者不能为空
        if (tags == null || tags.length == 0) {//
            return;
        }

        // 设置运行模式
        boolean pattern = false;
        String patternStr = "[DEV]";
        if (profiles.equals("pro") || profiles.equals("prohrb")) {
            pattern = true;
            patternStr = "[PRO]";
        }

        // Ios
        IosNotification iosNotification = IosNotification.newBuilder()
                // 详情
                .setAlert(title + ":" + alert)
                // 声音
                .setSound("default")
                // 拓展参数
                .addExtras(extras).build();

        // Android
        AndroidNotification androidNotification = AndroidNotification.newBuilder()
                // 标题
                .setTitle(title)
                // 详情
                .setAlert(alert)
                // 拓展参数
                .addExtras(extras).build();

        PushPayload payload = PushPayload.newBuilder()
                .setOptions(Options.newBuilder().setApnsProduction(pattern).setTimeToLive(60 * 60 * 24 * 10).build())
                // 平台
                .setPlatform(Platform.android_ios())
                // tag别名
                .setAudience(
                        tag_ands == null ? Audience.newBuilder().addAudienceTarget(AudienceTarget.tag(tags)).build()
                                : Audience.newBuilder().addAudienceTarget(AudienceTarget.tag(tags))
                                        .addAudienceTarget(AudienceTarget.tag_and(tag_ands)).build())
                // 提醒
                .setNotification(Notification.newBuilder()//
                        .addPlatformNotification(iosNotification)//
                        .addPlatformNotification(androidNotification)//
                        .build())
                .build();

        try {
            LOGGER.info(patternStr + "发送通知Notification开始");
            LOGGER.info("TAGS:" + ArrayUtils.toString(tags));
            JPushClient jPushClient = jpushConfig.getInstance(flag);
            ScheduleResult createSingleSchedule = jPushClient.createSingleSchedule("定时推送作业通知", date, payload);
            LOGGER.info(patternStr + "发送通知Notification结束:" + createSingleSchedule);
        } catch (Exception e) {
            // LOGGER.error("发送消息异常[PRO]", e);
            LOGGER.error(patternStr + "发送通知Notification异常:" + e.getMessage());
            if (e instanceof APIRequestException) {
                APIRequestException ee = (APIRequestException) e;
                if (ee.getErrorCode() == 2002) { throw new RuntimeException(e); }
            }
        }

    }
}
